package com.example.courseselect.web;

import javax.validation.Valid;

//import com.edu.hqu.courseselect.domain.Course;
import com.example.courseselect.domain.Student;
import com.example.courseselect.domain.course;
import com.example.courseselect.domain.course.Type;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

//import com.edu.hqu.courseselect.domain.StudentInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/message")
@SessionAttributes("message")
public class messagecontroller {
	@ModelAttribute//  ע     εķ        п         ִ  ǰ    ִ
	public void addcourseToModel(Model model) {
		List<course> courses = Arrays.asList(
				new course("高等数学",Type.REQUIRED),
				new course("离散数学", Type.REQUIRED),
				new course("python",Type.OPTION),
				new course("javaweb",Type.OPTION),
				new course("matlab",Type.OPTION)
		);
		Type[] types = course.Type.values();
		for (Type type : types) {
			model.addAttribute(type.toString().toLowerCase(),
					filterByType(courses, type));//  KEY-VALUE  ʽ        ӵ model
		}
	}
	@GetMapping
	public String ShowInfo(Model model) {
		model.addAttribute("message",new Student());
		return "message";
	}
	@PostMapping
	public String processInfo(@Valid @ModelAttribute("message") Student message, Errors errors) {
		if(errors.hasErrors()) {
			return "info";
		}
		log.info("Info submitted: " + message);
		return "course";
	}
	private List<course> filterByType(
			List<course> courses, course.Type type) {
		return courses
				.stream()
				.filter(x -> x.getType().equals(type))
				.collect(Collectors.toList());
	}

}
